const base = require("./../../base");
const math = require("mathjs");
const moment = require("moment");
const _ = require("lodash");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
        await super.isUserAuth();
    }

    /**
     *
     * @api {get} /shop/api/shop/order/service/index 售后理由列表
     * @apiDescription 售后理由列表
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} type        类型 0：售后 1：退款
     *
     * @apiSampleRequest /shop/api/shop/order/service/index
     *
     */
    async index() {
        const shopId = this.state.shop.id;
        const { type = 0 } = this.query;
        const service = await this.model("service")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("type", type);
                qb.where("status", 1);
            })
            .fetchAll();
        this.success(service);
    }

    /**
     *
     * @api {post} /shop/api/shop/order/service/apply 申请售后
     * @apiDescription 申请售后
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} id          订单id
     * @apiParam {Number} service_id  勾选理由id
     * @apiParam {Number} type        类型 0：售后 1：退款
     * @apiParam {Number} content     售后内容
     *
     * @apiSampleRequest /shop/api/shop/order/service/apply
     *
     */
    async apply() {
        const { id, service_id, type, content } = this.post;
        const shopId = this.state.shop.id;

        const order = await this.model("order")
            .query(qb => {
                qb.where("id", id);
                qb.where("shop_id", shopId);
            })
            .fetch();
        if (!order) {
            this.fail("参数错误");
            return;
        }
        if (order.check > 1) {
            this.fail("请等待审核");
            return;
        }
        if (
            Number(order.payment_id) !== 3 &&
            Number(order.pay_status) !== 1 &&
            Number(type) === 1
        ) {
            this.fail("该订单暂不能退款");
            return;
        }
        const service = await this.model("order_service")
            .forge({
                shop_id: shopId,
                order_id: id,
                service_id: service_id,
                content: content,
                type: type,
                status: 0
            })
            .save();

        await this.model("order")
            .forge({
                id: order.id,
                check: Number(type) ? 3 : 2
            })
            .save();
        this.success(service);
    }
};
